/**
 * 
 */
package com.servicecloud.filter;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;

/**
 * 
 *
 * @author Gavin<br>
 *         限流拦截器<br>
 *         令牌桶算法有开源的组件实现了，guava 2020年4月10日
 */
@Component
public class RateLimitFilter extends ZuulFilter {

	private static final RateLimiter RATE_LIMITER = RateLimiter.create(1);// 每秒钟放100个令牌

	/* 
	 */
	@Override
	public boolean shouldFilter() {
		return true;
	}

	/* 
	 */
	@Override
	public Object run() {
		System.err.println(1);
		if (!RATE_LIMITER.tryAcquire()) {// 如果没有拿到令牌就进行返回
			throw new RuntimeException("等哈，系统遭不住了，人太多了。稍等哈儿！");
			/*RequestContext ctx = RequestContext.getCurrentContext();
			HttpServletRequest request = ctx.getRequest();
			ctx.addZuulResponseHeader("Content-type", "application/json;charset=UTF-8");
			ctx.getResponse().setCharacterEncoding("UTF-8");
			System.out.println("请求地址:" + request.getRequestURI());
			ctx.setSendZuulResponse(false);
			String msg = "请求太多了，请等一哈再试。";
			ctx.setResponseBody(msg);
			ctx.setResponseStatusCode(HttpStatus.SC_BAD_GATEWAY);
			return msg;*/

		}
		return null;
	}

	/* 
	 */
	@Override
	public String filterType() {
		// TODO Auto-generated method stub
		return FilterConstants.PRE_TYPE;
	}

	/* 
	 */
	@Override
	public int filterOrder() {// 限流拦截器一般放在最前面SERVLET_DETECTION_FILTER_ORDER的优先级是最低的
		return FilterConstants.SERVLET_DETECTION_FILTER_ORDER - 1;
	}

}
